package centralRepository;

import java.util.ArrayList;

import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.Binding;
import org.omg.CosNaming.BindingHolder;
import org.omg.CosNaming.BindingIterator;
import org.omg.CosNaming.BindingIteratorHolder;
import org.omg.CosNaming.BindingListHolder;
import org.omg.CosNaming.BindingType;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;


public class Entry {
	
	public ArrayList entries;
	public String name;

	public Entry(String n){
		name = n;
		entries = new ArrayList();
	}

	public static Entry explore(String contextName,NamingContext context,int treeDepth) throws InvalidName, NotFound, CannotProceed, org.omg.CosNaming.NamingContextPackage.InvalidName{

		BindingListHolder blh = new BindingListHolder();
		BindingIteratorHolder bih = new BindingIteratorHolder();

		context.list(0,blh, bih);

		Entry entry = new Entry(contextName);

		System.out.println(contextName); 
		//binding iterator
		BindingIterator bit = bih.value;

		boolean remains = true;
		while(remains){
			BindingHolder biholder = new BindingHolder();
			remains = bit.next_one(biholder);
			Binding binding = biholder.value;

			NameComponent[] name = binding.binding_name;


			if(binding.binding_type == BindingType.nobject){
				if(name.length == 1){
					System.out.println("ID: " + name[0].id + " KIND: " + name[0].kind + " Depth: " + treeDepth);
					entry.entries.add(new Entry(name[0].id));
				}
			}else if(binding.binding_type == BindingType.ncontext){
				NamingContext tmpContext =  NamingContextHelper.narrow(context.resolve(binding.binding_name));
				NameComponent component = name[0];
				entry.entries.add(explore(component.id,tmpContext,treeDepth+1));
			}
		}
		return entry;
	}
}
